package com.zzvcom.doc.controller;


import com.zzvcom.doc.dto.RequestHtmlDTO;
import com.zzvcom.doc.html.CoreConvertOutHtml;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/html")
public class DocToHtmlController {

    /**
     * 验证测试例子
     * http://localhost/doc4js/html/convert_debug
     * http://localhost/doc4js/html/convert_debug?onlyCore=true
     * http://localhost/doc4js/html/convert_debug?onlyCore=true&mathjax=true
     *
     * @return
     * @throws IOException
     */
    @GetMapping(value = "/convert_debug", produces = MediaType.TEXT_HTML_VALUE)
    @ResponseBody
    public String convertDebug(RequestHtmlDTO requestHtmlDTO, HttpServletRequest httpServletRequest) throws IOException {
        String inputfilepath = "D:/new/docxjhtml/doc/section_test.docx";
        //requestHtmlDTO.setSaveFileDebug(true);
        //不要转换公式的javascript的配置
        // requestHtmlDTO.setMathjax(true);
        //requestHtmlDTO.setOnlyCore(true);
        requestHtmlDTO.setContextPath(httpServletRequest.getContextPath());
        if (requestHtmlDTO.getStylePrefix() == null || requestHtmlDTO.getStylePrefix().trim().length() == 0) {
            requestHtmlDTO.setStylePrefix("s" + System.nanoTime() + "_");
        }
        try (FileInputStream inputStream = new FileInputStream(inputfilepath)) {
            String html = CoreConvertOutHtml.process(inputStream, requestHtmlDTO);
            return html;
        }
    }

    /**
     * http://localhost/doc4js/html/convert_upload
     * @param file
     * @param requestHtmlDTO
     * @param httpServletRequest
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/convert_upload", produces = MediaType.TEXT_HTML_VALUE)
    @ResponseBody
    public String convertUpload(@RequestParam("file") MultipartFile file,
                                RequestHtmlDTO requestHtmlDTO, HttpServletRequest httpServletRequest) throws IOException {
        // 设置请求上下文路径
        requestHtmlDTO.setContextPath(httpServletRequest.getContextPath());

        // 如果没有设置样式前缀，则生成一个唯一的前缀
        if (requestHtmlDTO.getStylePrefix() == null || requestHtmlDTO.getStylePrefix().trim().length() == 0) {
            requestHtmlDTO.setStylePrefix("s" + System.nanoTime() + "_");
        }

        // 将上传的文件转换为输入流并处理
        try (InputStream inputStream = file.getInputStream()) {
            String html = CoreConvertOutHtml.process(inputStream, requestHtmlDTO);
            return html;
        }
    }

}
